import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:expandable/expandable.dart';
import 'package:shop/shop/merchant/Index.dart';
import 'package:shop/shop/merchant/MyOrderList.dart';
import 'package:url_launcher/url_launcher.dart';
class OrderIng extends StatefulWidget {
  OrderIng({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _OrderIng createState() => _OrderIng();
}

class _OrderIng extends State<OrderIng> {

  bool isShow=true;
  SharedPreferences prefs;
  String merchantID=""; //商户ID
  List orderList=[];    //进行中订单集合
  String  mType='';     //店铺类型

  //初始化数据
  @override
  void initState() {
    super.initState();
    _getOrder();
  }

  // 加载商户进行中的订单
  _getOrder() async{
    prefs = await SharedPreferences.getInstance();
    merchantID = prefs.getString("merchantID");
    mType=prefs.getString("mType");
    var res  =await HttpUtil().get("/waimai/mOder/getMerchantOrder?mId="+merchantID+"&orStatus=1");
    if(res['code']==200){
      orderList=res['data'];
    }
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      body: ExpandableTheme(
        data: const ExpandableThemeData(
          iconColor: Colors.blue,
          useInkWell: true,
        ),
        child: ListView(
          // physics: const BouncingScrollPhysics(),
          // children: <Widget>[
          //   Card1(),
          //   Card1(),
          //   Card1(),
          // ],
          children: [
            _getOrders()
          ],
        ),
      ),
    );
  }

  //得订单
  _getOrders(){
    List<Widget> x = [];
    for(int i=0;i<orderList.length;i++){
      x.add(
        ExpandableNotifier(
          child: Padding(
            padding: const EdgeInsets.all(0),
            child: Card(
              clipBehavior: Clip.antiAlias,
              child: Column(
                children: <Widget>[
                  SizedBox(
                    // height: 150,
                    child: Container(
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(orderList[i]['address']['adName']),
                              GestureDetector(child: Icon(Icons.phone),onTap: () async {
                                await launch("tel:"+orderList[i]['address']['adPhone']);
                              },)
                            ],
                          ),
                          SizedBox(height: 10 ,),
                          Row(children: [Expanded(child: Text(orderList[i]['address']['addressDetail']))],),
                          Divider(),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("正在备餐"),
                              GestureDetector(child: Container(
                                padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),child: Text("出餐完成"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),
                              ),onTap: () async{
                                print("订单"+orderList[i]['id']+"出餐完成"+" 商家ID："+merchantID);
                                var res  =await HttpUtil().get("/waimai/mOder/merchantChucan?merchantId="+merchantID+"&orId="+orderList[i]['id']);
                                if(res['code']==200){
                                  Fluttertoast.showToast(
                                    msg: "出餐完成",
                                  );
                                  // 刷新页面
                                 MyRoute.replace(Index(showIndex: "0",mType: mType,));
                                  // setState(() {
                                  //   _getOrder();
                                  // });
                                }else{
                                  Fluttertoast.showToast(
                                    msg: res['msg'],
                                  );
                                }
                              },)
                            ],
                          ),
                          SizedBox(height: 10 ,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text(orderList[i]['rider']==null ? "" : orderList[i]['rider']['qsName']),
                                  Container(padding: EdgeInsets.symmetric(vertical: 2,horizontal:5),child: Text("骑手",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,color: Colors.blueAccent),)
                                ],
                              ),
                              GestureDetector(child: Icon(Icons.phone),onTap: () async {
                                await launch("tel:"+orderList[i]['rider']=="" ? "" : orderList[i]['rider']['phone']);
                              },)
                            ],
                          ),
                          SizedBox(height: 10 ,),
                          Row(
                            children: [Text("16:23  骑手已接单")],
                          ),
                        ],
                      ),
                      decoration: BoxDecoration(
                        // color: Colors.orangeAccent,
                        // shape: BoxShape.rectangle,
                      ),
                    ),
                  ),
                  ScrollOnExpand(
                    scrollOnExpand: true,
                    scrollOnCollapse: false,
                    child: ExpandablePanel(
                      theme: const ExpandableThemeData(
                        headerAlignment: ExpandablePanelHeaderAlignment.center,
                        tapBodyToCollapse: true,
                      ),
                      header: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          "商品("+orderList[i]['morderDetailList'].length.toString()+")",
                          style: Theme.of(context).textTheme.body2,
                        )
                      ),
                      expanded: Column(   // 展开的内容
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _getOrderDetail(orderList[i]['morderDetailList'])
                        ],
                      ),
                      builder: (_, collapsed, expanded) {
                        return Padding(
                          padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                          child: Expandable(
                            collapsed: collapsed,
                            expanded: expanded,
                            theme: const ExpandableThemeData(crossFadePoint: 0),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          )
        )
      );
    }
    return Container(
      child: Column(children: x),
    );
  }

  //得订单详情
  _getOrderDetail(orderDetailList){
    List<Widget> x = [];
    for(int i=0;i<orderDetailList.length;i++){
      x.add(
        Row(
          children: [
            Container(
              width: ScreenUtil().setWidth(230),
              height: ScreenUtil().setHeight(45),
              child: Row(
                children: [
                  Expanded(child: Text(orderDetailList[i]['mgoods']['gname']),),
                ],
              ),
            ),
            // Text(orderDetailList[i]['mgoods']['gname']),
            Text("*"+orderDetailList[i]['odNum'].toString()),
            Text("￥"+orderDetailList[i]['odCost'].toString()),
          ],mainAxisAlignment: MainAxisAlignment.spaceBetween
        )
      );
    }
    return Container(
      child: Column(children: x),
    );
  }
}

class Card1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ExpandableNotifier(
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Card(
            clipBehavior: Clip.antiAlias,
            child: Column(
              children: <Widget>[
                SizedBox(
                  // height: 150,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("张无忌"),
                           GestureDetector(child: Icon(Icons.phone),onTap: () async{
                             launch("tel:"+'110'); // 模拟器直接调用，不要判断.真机还不知道是否可行
                             // if( await canLaunch("tel:"+'110')){
                             // await launch("tel:"+'10');
                             // }else{
                             // throw "拨号失败"; // 模拟器会失败，真机可以拨号
                             // }
                           },)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(children: [Text("天元区珠江北路幸福大厦")],),
                        Divider(),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("正在备餐"),
                            Container(padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),child: Text("出餐完成"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("王重阳"),
                                Container(padding: EdgeInsets.symmetric(vertical: 2,horizontal:5),child: Text("骑手"),decoration: BoxDecoration(border: Border.all(color: Colors.black , width: 0) ,),)
                              ],
                            ),
                            GestureDetector(child: Icon(Icons.phone),onTap: () async{
                              launch("tel:"+'120'); // 模拟器直接调用，不要判断.真机还不知道是否可行
                              // if( await canLaunch("tel:"+'120')){
                              // await launch("tel:"+'120');
                              // }else{
                              // throw "拨号失败"; // 模拟器会失败，真机可以拨号
                              // }
                            },)
                          ],
                        ),
                        SizedBox(height: 10 ,),
                        Row(
                          children: [Text("16:23  骑手已接单")],
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      // color: Colors.orangeAccent,
                      // shape: BoxShape.rectangle,
                    ),
                  ),
                ),
                ScrollOnExpand(
                  scrollOnExpand: true,
                  scrollOnCollapse: false,
                  child: ExpandablePanel(
                    theme: const ExpandableThemeData(
                      headerAlignment: ExpandablePanelHeaderAlignment.center,
                      tapBodyToCollapse: true,
                    ),
                    header: Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          "商品(3)",
                          style: Theme.of(context).textTheme.body2,
                        )),
                    // collapsed: Text(   // 收起的文字内容
                    //   loremIpsum,
                    //   softWrap: true,
                    //   maxLines: 2,
                    //   overflow: TextOverflow.ellipsis,
                    // ),
                    expanded: Column(   // 展开的内容
                      crossAxisAlignment: CrossAxisAlignment.start,
                      // children: <Widget>[
                      //   for (var _ in Iterable.generate(5))
                      //     Padding(
                      //         padding: EdgeInsets.only(bottom: 10),
                      //         child: Text(
                      //           loremIpsum,
                      //           softWrap: true,
                      //           overflow: TextOverflow.fade,
                      //         )),
                      // ],
                      children: [
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("辣椒炒肉"),Text("*1"),Text("￥19")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                        Row(children: [Text("小计"),Text("￥22")],mainAxisAlignment: MainAxisAlignment.spaceBetween,),
                      ],
                    ),
                    builder: (_, collapsed, expanded) {
                      return Padding(
                        padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                        child: Expandable(
                          collapsed: collapsed,
                          expanded: expanded,
                          theme: const ExpandableThemeData(crossFadePoint: 0),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        )
    );
  }
}